<?php 
/**
 * 分类管理模型
 */
class CategoryModel extends Model{
	public $table = 'category';

	public $validate = array(

		array('cname','nonull','分类名称不能为空',2,1)

		);

	/**
	 * 添加分类
	 */
	public function add_cname(){
		if (!$this->create()) return false;
		// p(Q('post.'));die;
		$tid = Q('post.tid',0,'intval');
		$pid = Q('post.pid',0,'intval');
		// 提交过来的分类变为数组
		$category_arr = explode('|',Q('post.cname'));
		// p($category_arr);
		foreach ($category_arr as $cname) {
			$this->add(array('cname'=>$cname,'pid'=>$pid,'type_tid'=>$tid));
		}
		return true;

	}
	/**
	 * 编辑分类
	 */
	public function edit_cname(){
		if (!$this->create()) return false;
		$this->update();
		return true;
	}



	// 通过cid获得商品ID
	public function get_gid($cid){
		// 获得所有子集，包括当前cid
		$cids = $this->get_son($cid);
		// 调取缓存
		$gids = S("{$cid}_gid");
		// 如果$gids没有时，查询一遍goods表,获得gid
		if (!$gids) {
			$gids = K('Goods')->where("category_cid IN (" . implode(',',$cids) . ")")->getField('gid',true);
			// 缓存1分钟
			S("{$cid}_gid",$gids,60);
		}
		return $gids;
	}
	// 获得对应商品分类
	public function get_c_data($cid,$rows){
		$cids = $this->_get_all_son($this->all(),$cid);
    	foreach (array_slice($cids,0,$rows) as $k => $v_cid) {
    		$c_data[] = $this->where("cid='{$v_cid}'")->find();
    	}

		return $c_data;
	}
	// 获得所有子集,包括当前cid
	public function get_son($cid){
		$cids = $this->_get_all_son($this->all(),$cid);
		$cids[] = $cid;
		return $cids;
	}
	/**
	 * 递归获得所有子集，不包括自己
	 */
	public function _get_all_son($data,$cid){
		$temp = array();
		foreach ($data as $k => $v) {
			if ($v['pid'] == $cid) {
				$temp[] = $v['cid'];
				$temp = array_merge($temp,$this->_get_all_son($data,$v['cid']));
			}
		}
		return $temp;
	}



	// 通过cid获得商品
	public function get_goods($cid,$last_gids){
		if ($last_gids) {
			// return K("Goods")->where( "category_cid='{$cid}' AND gid IN(". implode(',',$last_gids) .")")->all();
			return K("Goods")->where( "gid IN(". implode(',',$last_gids) .")")->all();
		}else{
			return 0;
		}
    	// return K("Goods")->where( "category_cid='{$cid}' AND gid IN(". implode(',',$last_gids) .")")->all();
	}

}




















 ?>